import React, { Component } from 'react';
import PropTypes from 'prop-types';
import CascaderSelect from '@/components/CascaderSelect';
import MultiSelectableTreeMenus from '@/components/MultiSelectableTreeMenus';
import SingleSelectableTreeMenus from '@/components/SingleSelectableTreeMenus';

class CascaderSelectableMenus extends Component {

  static defaultProps = {
    type: 'multi'
  };

  constructor(props) {
    super(props);
    this.menuMap = {}
    this.state = {
      $selectedHandle: -1,
      category: '',
    }
  }

  buildMenuMap = (treeMenus) => {
    if(treeMenus) {
      for(let i=0; i<treeMenus.length; i++) {
        const { $typeSpec } = treeMenus[i];
        if($typeSpec.endsWith('EnergyArea') || $typeSpec.endsWith('EnergyCategory')) {
          if(treeMenus[i].children && treeMenus[i].children.length > 0) {
            if(treeMenus[i].children[0].$typeSpec.endsWith('Group')||treeMenus[i].children[0].$typeSpec.endsWith('TreeMenuItem')) {
              this.menuMap[treeMenus[i].$handle] = treeMenus[i].children;
            } else {
              this.buildMenuMap(treeMenus[i].children);
            }
          }
        }
      }
    }
  }

  menuChange = ($handles) => {
    const $selectedHandleLabel = $handles&&$handles.length>0?$handles[$handles.length-1]:-1;
    const $selectedHandles = $selectedHandleLabel.split('||');
    this.setState({ $selectedHandle: $selectedHandles[0], category: $selectedHandles[1]});
  }

  componentDidMount() {
    this.buildMenuMap(this.props.treeMenus);
  }

  render() {
    const { treeMenus, type } = this.props;
    const { $selectedHandle, category } = this.state;
    return (
      <>
        <CascaderSelect treeMenus={treeMenus} menuChangeCallback={this.menuChange} />
        {$selectedHandle!==-1?(type=='multi'?<MultiSelectableTreeMenus menuList={this.menuMap[$selectedHandle]} onSelectedMenuChange={($selectedHandle)=>this.props.onSelectedMenuChange($selectedHandle, category)}/>:
        <SingleSelectableTreeMenus menuList={this.menuMap[$selectedHandle]} onSelectedMenuChange={($selectedHandle)=>this.props.onSelectedMenuChange($selectedHandle, category)}/>):''}
      </>
    );
  }
}

CascaderSelectableMenus.propTypes = {
  treeMenus: PropTypes.array.isRequired,
  onSelectedMenuChange: PropTypes.func.isRequired,
  type: PropTypes.string
};

export default CascaderSelectableMenus;
